package main.activities;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import main.db.entities.FavoriteAdvert;
import main.db.entities.dao.FavoriteAdvertDAO;
import model.advertisers.Advertiser;
import model.advertisers.Leboncoin;
import model.advertisers.Vivastreet;
import model.domain.Advert;
import model.domain.Category;
import model.domain.Region;
import model.reference.Categories;
import model.reference.Regions;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.objects.LoaderImageView;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;

//TODO this class is too big.... really?
public class mainActivity extends Activity {

	// TODO to change with a file saved
	// elements caracterising the search
	private List<Advertiser> listAdvertisers = new ArrayList<Advertiser>();
	private Advertiser currentAdvertiser;
	ArrayList<HashMap<String, String>> listItem;
	private String category = Categories.ALL.getName();
	private String region = Regions.ALL.getName();
	private String keyWords;
	private List<Advert> adverts;

	private boolean isFinished = false;

	// detail
	private String urlMail;

	// android entities

	// main
	private EditText editTextSearch;
	private ListView myListView;
	private TextView noResult;

	// websites
	private TextView advertiserTextView;
	private CheckBox allAdvertisersCheckBox;
	private CheckBox leboncoinCheckBox;
	private CheckBox vivaSteetCheckBox;

	// category and location
	private TextView textViewCategories;
	private TextView textViewLocations;
	private Spinner spinnerCategories;
	private Spinner spinnerLocations;

	// Constant for preferences
	private final String CATEGORY_PREF = "categoriesAnnonceCompare";
	private final String LOCATION_PREF = "locationsAnnonceCompare";
	
	//temp variables used for saving
	private String tempHyperLinkDetail;
	private String tempAdvertName;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		
		

		goToMain();
	}

	public void goToMain() {
		setContentView(R.layout.main);

		// main
		editTextSearch = (EditText) findViewById(R.id.editTextSearch);
		myListView = (ListView) findViewById(R.id.listviewperso);
		noResult = (TextView) findViewById(R.id.noResult);

		displayList();
		
		//favorite adverts
		//TODO to implement
		FavoriteAdvertDAO favoriteAdvertDAO=new FavoriteAdvertDAO(this);
		favoriteAdvertDAO.open();
		List<FavoriteAdvert> listFavoriteAdverts=favoriteAdvertDAO.getFavoriteAdverts();
		
		System.out.println();
		favoriteAdvertDAO.close();
	}

	private void goToWebSite() {

		// websites

		setContentView(R.layout.websites);

		allAdvertisersCheckBox = (CheckBox) findViewById(R.id.allAdvertisers);
		leboncoinCheckBox = (CheckBox) findViewById(R.id.leboncoin);
		vivaSteetCheckBox = (CheckBox) findViewById(R.id.vivastreet);
		advertiserTextView = (TextView) findViewById(R.id.advertisers);
		advertiserTextView.setTextSize(30);
	}

	public void saveWebsitesOnClick(View view) {
		listAdvertisers.clear();
		if (allAdvertisersCheckBox.isChecked()) {

			choiceForAll();

		} else {
			if (leboncoinCheckBox.isChecked()) {
				listAdvertisers.add(new Leboncoin());

			}
			if (vivaSteetCheckBox.isChecked()) {
				listAdvertisers.add(new Vivastreet());
			}
		}

		goToMain();

	}

	private void choiceForAll() {
		listAdvertisers.add(new Vivastreet());
		listAdvertisers.add(new Leboncoin());

	}

	public void saveCategoriesOnClick(View view) {
		category = (String) spinnerCategories
				.getItemAtPosition(spinnerCategories.getSelectedItemPosition());

		Editor prefs = getPreferences(0).edit();
		prefs.putString(CATEGORY_PREF, category);
		prefs.commit();

		goToMain();
	}

	public void saveLocationsOnClick(View view) {
		region = (String) spinnerLocations.getItemAtPosition(spinnerLocations
				.getSelectedItemPosition());

		Editor prefs = getPreferences(0).edit();
		prefs.putString(LOCATION_PREF, region);
		prefs.commit();

		goToMain();
	}

	public void launchSearchClickHandler(View view) {

		if (editTextSearch.getText().toString() != null
				&& !editTextSearch.getText().toString().equals("")) {
			keyWords = (String) editTextSearch.getText().toString();
		} else {
			keyWords = "";
		}

		findAdverts();

	}

	// TODO put a loading there
	public void findAdverts() {

		listItem = new ArrayList<HashMap<String, String>>();
		HashMap<String, String> map;
		adverts = new ArrayList<Advert>();
		long start = System.currentTimeMillis();
		Log.i("listAdvertisers.size()  ",
				String.valueOf(listAdvertisers.size()));

		if (listAdvertisers.size() == 0) {
			choiceForAll();
		}

		for (int i = 0; i < listAdvertisers.size(); i++) {
			Advertiser myAdvertiser = listAdvertisers.get(i);
			Log.i("myAdvertiser  ", myAdvertiser.toString());
			myAdvertiser.setLocation(myAdvertiser.getAdvertiserReference()
					.getLocalisation().get(region));
			myAdvertiser.setKeyWord(keyWords);
			myAdvertiser.setCategory(myAdvertiser.getAdvertiserReference()
					.getCategories().get(category));
			myAdvertiser.setKind("offres");
			Log.i("URLsearch", myAdvertiser.getUrlResearch());

			try {
				adverts.addAll(myAdvertiser.findAdverts());

			} catch (Exception e1) {
				Log.i("findAdverts exception ", e1.getMessage());
				e1.printStackTrace();
			}

		}

		long end = System.currentTimeMillis();
		long timeSpent = (start - end);
		Log.d("Time to find all adverts: ", String.valueOf(timeSpent));

		for (int i = 0; i < adverts.size(); i++) {
			adverts.get(i).reparseAllAtributes();
			map = new HashMap<String, String>();

			if (adverts.get(i).getName() != null) {
				map.put("description", adverts.get(i).getName());
			}
			if (adverts.get(i).getPrice() != null) {
				map.put("price", adverts.get(i).getPrice());
			}
			if (adverts.get(i).getTown() != null) {
				map.put("location", adverts.get(i).getTown());
			}
			if (adverts.get(i).getDate() != null) {
				map.put("date", adverts.get(i).getDate());
			}

			map.put("id", String.valueOf(adverts.get(i).getId()));

			listItem.add(map);

		}

		displayList();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		new MenuInflater(getApplication()).inflate(R.menu.menu, menu);
		return (super.onCreateOptionsMenu(menu));
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		if (item.getItemId() == R.id.websites) {
			goToWebSite();
		} else if (item.getItemId() == R.id.geographical) {
			goToLocations();
		} else if (item.getItemId() == R.id.categories) {
			goToCategories();
		}

		return (super.onOptionsItemSelected(item));

	}

	private void goToCategories() {
		setContentView(R.layout.categories);

		SharedPreferences prefs = getPreferences(0);
		String myCategory = (String) prefs.getAll().get(CATEGORY_PREF);

		// categorie and location part
		textViewCategories = (TextView) findViewById(R.id.categoriesMessage);
		textViewCategories.setTextSize(30);

		spinnerCategories = (Spinner) findViewById(R.id.spinnerCategories);
		List<CharSequence> featuresList = new ArrayList<CharSequence>();
		ArrayAdapter<CharSequence> featuresAdapter = new ArrayAdapter<CharSequence>(
				this, android.R.layout.simple_spinner_item, featuresList);
		featuresAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerCategories = ((Spinner) mainActivity.this
				.findViewById(R.id.spinnerCategories));
		spinnerCategories.setAdapter(featuresAdapter);

		List<Category> listCategories = Categories.CATEGORIES_LIST;

		if (myCategory != null) {
			for (int i = 0; i < listCategories.size(); i++) {
				if (listCategories.get(i).isRoot()
						&& listCategories.get(i).getName().equals(myCategory)) {
					featuresAdapter.add(listCategories.get(i).getName());
				}

			}
		}

		for (int i = 0; i < listCategories.size(); i++) {
			if (listCategories.get(i).isRoot()
					&& (myCategory == null | !listCategories.get(i).getName()
							.equals(myCategory))) {
				featuresAdapter.add(listCategories.get(i).getName());

			}

		}

	}

	private void goToLocations() {

		setContentView(R.layout.location);

		textViewLocations = (TextView) findViewById(R.id.locations);
		textViewLocations.setTextSize(30);

		SharedPreferences prefs = getPreferences(0);
		String myLocation = (String) prefs.getAll().get(LOCATION_PREF);

		spinnerLocations = (Spinner) findViewById(R.id.spinnerLocations);
		List<CharSequence> featuresListLocations = new ArrayList<CharSequence>();
		ArrayAdapter<CharSequence> featuresAdapterLocations = new ArrayAdapter<CharSequence>(
				this, android.R.layout.simple_spinner_item,
				featuresListLocations);
		featuresAdapterLocations
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerLocations = ((Spinner) mainActivity.this
				.findViewById(R.id.spinnerLocations));
		spinnerLocations.setAdapter(featuresAdapterLocations);

		List<Region> listLocations = Regions.REGION_LIST;

		if (myLocation != null) {
			for (int i = 0; i < listLocations.size(); i++) {
				if (listLocations.get(i).getName().equals(myLocation)) {
					featuresAdapterLocations
							.add(listLocations.get(i).getName());
				}

			}
		}

		for (int i = 0; i < listLocations.size(); i++) {

			if (myLocation == null
					| !listLocations.get(i).getName().equals(myLocation)) {
				featuresAdapterLocations.add(listLocations.get(i).getName());
			}

		}

	}

	
	public void displayList() {

		if (listItem != null && listItem.size() == 0) {
			noResult.setVisibility(View.VISIBLE);
		}

		if (listItem != null && listItem.size() > 0) {
			SimpleAdapter mSchedule = new SimpleAdapter(this.getBaseContext(),
					listItem, R.layout.advert, new String[] { "description",
							"price", "location", "date" }, new int[] {
							R.id.description, R.id.price, R.id.location,
							R.id.date });

			myListView.setAdapter(mSchedule);

			myListView.setOnItemClickListener(new OnItemClickListener() {
				@SuppressWarnings("unchecked")
				public void onItemClick(AdapterView<?> a, View v, int position,
						long id) {
					HashMap<String, String> map = (HashMap<String, String>) myListView
							.getItemAtPosition(position);

					double idAvert = Double.valueOf(map.get("id"));
					getDetail(idAvert);

				}
			});
		}
	}

	public void getDetail(double id) {
		setContentView(R.layout.advertdetail);

		LinearLayout loaderImage = (LinearLayout) this
				.findViewById(R.id.loaderImage);
		LinearLayout loaderPhoneImg = (LinearLayout) this
				.findViewById(R.id.loaderPhoneImg);
		TextView price = (TextView) this.findViewById(R.id.price);
		TextView location = (TextView) this.findViewById(R.id.location);
		TextView date = (TextView) this.findViewById(R.id.date);
		TextView detailDescription = (TextView) this
				.findViewById(R.id.detailDescription);
		TextView name = (TextView) this.findViewById(R.id.name);

		Advert anAdvert = Advert.findById(adverts, id);
		anAdvert.getMoreDetail();

		name.setText(anAdvert.getName());

		price.setText(anAdvert.getPrice());
		location.setText(anAdvert.getTown());
		date.setText(anAdvert.getDate());

		detailDescription.setText(anAdvert.getDetail());
		
		tempHyperLinkDetail = anAdvert.getHyperlinkDetail();
		tempAdvertName=anAdvert.getName();

		urlMail = anAdvert.getUrlContact();

		try {
			if (anAdvert.getHyperlinkPictureHD() != null
					&& anAdvert.getHyperlinkPictureHD() != "") {
				final LoaderImageView image = new LoaderImageView(this,
						anAdvert.getHyperlinkPictureHD());
				image.setLayoutParams(new LayoutParams(
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
				loaderImage.addView(image);

				// TODO adapt this
				// final LoaderImageView phoneImage = new LoaderImageView(this,
				// anAdvert.getOwner().getPhoneNumber().toString());
				// image.setLayoutParams(new LayoutParams(
				// LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
				//
				// loaderPhoneImg.addView(phoneImage);

				final TextView phoneTextView = (TextView) findViewById(R.id.phoneRecon);
				String linkOrPhone = anAdvert.getOwner().getPhoneNumber()
						.toString();
				phoneTextView.setText(linkOrPhone);

			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void beforeDetailClickHandler(View view) {
		goToMain();
	}

	public void saveAnnounceClickHandler(View view) {

		// TODO to implement
		FavoriteAdvertDAO aFavoriteAdvertDAO=new FavoriteAdvertDAO(this);
		
		FavoriteAdvert aFavoriteAdvert=new FavoriteAdvert(this.tempAdvertName,this.tempHyperLinkDetail);
		
		aFavoriteAdvertDAO.open();
		aFavoriteAdvertDAO.insertFavoriteAdvert(aFavoriteAdvert);
		aFavoriteAdvertDAO.close();
		goToMain();
	}

	public void sendMailHandler(View view) {

		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setData(Uri.parse(urlMail));
		startActivity(i);
	}
}